﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Ithalat
{
    public partial class MasrafByMusteri : XForm
    {
        public MasrafByMusteri()
        {
            InitializeComponent();
        }

        string REF
        {
            get
            {
                return "KRB.T" + (((DateTime)beiAy1.EditValue).Year % 10).ToStr();
            }
        }

        private void MasrafByMusteri_Load(object sender, EventArgs e)
        {
            DateTime GecenAy = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
            beiAy1.EditValue = GecenAy;


            beiAy1.EditValue = new DateTime(2015, 1, 1);
            beiAy2.EditValue = new DateTime(2016, 1, 1);
            //beiAy1.EditValueChanged += beiAy_EditValueChanged;

            gridView1.Init("GetImportList3x", beiAy1.EditValue.ToDate(), beiAy2.EditValue.ToDate(), txtReferans.EditValue.ToStr(), WhoAmI, REF);
            gridView1.AddDetailGrid(gridView2, "CustomerId");

            foreach (DataRow r in AppSession.Lookups.HesapPlani.Rows)
            {
                string hp = r["HesapPlaniId"].ToStr();

                if (gridView1.Columns.Contains(gridView1.Columns[hp]))
                {
                    gridView1.FormatAsNumber(1, hp);
                    gridView1.AddSummary(hp);
                    gridView1.SetCaptions(hp + ":" + r["Abbr"].ToStr());
                    gridView1.Columns[hp].ToolTip = r["Aciklama"].ToStr();  // r["HesapKodu"].ToStr() + ". " + r["Name"].ToStr();
                }

                if (gridView2.Columns.Contains(gridView2.Columns[hp]))
                {
                    gridView2.FormatAsNumber(1, hp);
                    gridView2.AddSummary(hp);
                    gridView2.SetCaptions(hp + ":" + r["Abbr"].ToStr());
                    gridView2.Columns[hp].ToolTip = r["Aciklama"].ToStr();  // r["HesapKodu"].ToStr() + ". " + r["Name"].ToStr();
                }
            }

            gridView1.RowCellStyle += gridView1_RowCellStyle;
            gridView2.RowCellStyle += gridView1_RowCellStyle;

            gridView1.MakeReadOnly();
            gridView2.MakeReadOnly("FaturalanacakTutar", "DovizCinsi1Id");
            gridView1.MakeColumnInvisible("Customer");
            gridView2.MakeColumnInvisible("Ay", "Oran", "Musteri", "Sezon", "KumasMasrafi", "Tarama", "FaturaId", "idosya");
            gridView2.Columns["OranM"].VisibleIndex = 100;
            gridView2.Columns["OranM"].ToolTip = "Müşterinin ilgili faturadaki payı";
            gridView2.FormatAsPercentage("OranM");
            gridView1.FormatAsNumber(1, "ToplamMasraf", "KumasMasrafi", "YuklenenMt");
            gridView2.FormatAsNumber(1, "ToplamMasraf", "KumasMasrafi", "LineTotals", "FaturaToplami", "Miktar", "YuklenenMt", "FaturalanacakTutar", "FaturalananTutar");
            gridView1.AddSummary("ToplamMasraf", "KumasMasrafi", "YuklenenMt");
            gridView2.AddSummary("ToplamMasraf", "KumasMasrafi", "LineTotals", "FaturaToplami", "Miktar", "YuklenenMt", "FaturalanacakTutar", "FaturalananTutar");
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;

            gridView1.FormatAsNumber(3, "MetreBasinaMasraf");
            gridView2.FormatAsNumber(3, "MetreBasinaMasraf");

            ((RepositoryItemDateEdit)beiAy1.Edit).CalendarView = CalendarView.TouchUI;
            ((RepositoryItemDateEdit)beiAy1.Edit).Mask.EditMask = "MM/yyyy"; //dd
            ((RepositoryItemDateEdit)beiAy1.Edit).Mask.UseMaskAsDisplayFormat = true;

            ((RepositoryItemDateEdit)beiAy2.Edit).CalendarView = CalendarView.TouchUI;
            ((RepositoryItemDateEdit)beiAy2.Edit).Mask.EditMask = "MM/yyyy"; //dd
            ((RepositoryItemDateEdit)beiAy2.Edit).Mask.UseMaskAsDisplayFormat = true;

            gridView1.SetViewCaption("Müşteri Bazlı Masraf Dağılımı");
            gridView2.SetViewCaption("Seçili Müşterinin Masraf Detayı");
            splitContainerControl1.AutoSize();
            btnGetir.ItemClick += btnGetir_ItemClick;

            gridView1.ShowOnlyNonblankColumns();
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

            GridManager gm = GridManager.GetManager(gridView2);
            if (ytk(226))
            {
                gm.GridMenu.AddMenu("Fiyatlara eklendi", FiyatlaraEklendi);
                gm.GridMenu.AddMenu("Faturalanacak", Faturalanacak);
                gm.GridMenu.AddMenu("İhracat Faturasına Eklenecek", IhracatFaturasinaEklenecek);
                gm.GridMenu.AddMenu("Üreticiye Faturalanacak", UreticiyeFaturalanacak);
                gm.GridMenu.AddMenu("Faturalanmayacak", Faturalanmayacak);
            }

            gridView2.CustomRowCellEdit += gridView2_CustomRowCellEdit;

            //riHyperLink.SingleClick = false;
            gridView2.Columns["KarbelInvNo"].ColumnEdit = riHyperLink;
            gridView2.Columns["REFERANS"].ColumnEdit = riHyperLink;
            gridView2.RowCellClick += gridView2_RowCellClick;

            btnKaydet.ItemClick += btnKaydet_ItemClick;
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView2.EndEditing();
            ExecuteNonQuery("UpdMasrafFaturala_Tutar", gridView2.SerializeChanges());
            gridView2.BestFitColumns();
        }


        RepositoryItemHyperLinkEdit riHyperLink = new RepositoryItemHyperLinkEdit();
        DevExpress.XtraEditors.Repository.RepositoryItemTextEdit edit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();

        void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            Cursor.Current = Cursors.WaitCursor;

            DataRow dr = gridView2.GetDataRow(e.RowHandle);

            switch (e.Column.FieldName)
            {
                case "KarbelInvNo":
                    string FATURANO = dr["KarbelInvNo"].ToStr();
                    if (FATURANO != string.Empty &&
                        dr["Tarama"].ToStr() != string.Empty)
                    {
                        DataTable dtDosya = ExecuteDataTable("GetFaturaPhoto", FATURANO);

                        byte[] bytes = (byte[])dtDosya.Rows[0]["Dosya"];
                        string FileName = FATURANO + ".png";

                        DevTeam.FileManager.RunTempFile(FileName, bytes);
                    }
                    break;

                case "REFERANS":
                    string REFERANS = dr["REFERANS"].ToStr();
                    if (REFERANS != string.Empty &&
                        dr["idosya"].ToStr() != string.Empty)
                    {
                        DataTable dtDosya = ExecuteDataTable("GetIthalatDosya", REFERANS);

                        byte[] bytes = (byte[])dtDosya.Rows[0]["Dosya"];
                        string FileName = dtDosya.Rows[0]["FileName"].ToStr();

                        DevTeam.FileManager.RunTempFile(FileName, bytes);
                    }
                    break;
            }


            Cursor.Current = Cursors.Default;
        }

        void gridView2_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (e.Column.FieldName == "KarbelInvNo")
                if (gridView2.GetRowCellValue(e.RowHandle, "Tarama") == DBNull.Value)
                    e.RepositoryItem = edit;

            if (e.Column.FieldName == "REFERANS")
                if (gridView2.GetRowCellValue(e.RowHandle, "idosya") == DBNull.Value)
                    e.RepositoryItem = edit;
        }

        void FiyatlaraEklendi(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show(gridView2.GetSelectedValues("FaturaId"), "FiyatlaraEklendi olarak işaretlenecek faturalar", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                ExecuteNonQuery("UpdMasrafFaturala", GetLines(), "FiyatlaraEklendi", WhoAmI);
                foreach (int rh in gridView2.GetSelectedRows())
                    gridView2.SetRowCellValue(rh, "Durum", "FiyatlaraEklendi");
                gridView2.BestFitColumns();
            }
        }

        private string GetLines()
        {
            int CustomerId = gridView1.GetFocusedDataRow()["CustomerId"].ToInt();
            DataTable dt = new DataTable();
            dt.Columns.Add("FaturaId", typeof(int));
            dt.Columns.Add("CustomerId", typeof(int));
            dt.Columns.Add("REFERANS", typeof(string));
            dt.Columns.Add("GonderenId", typeof(int));
            dt.Columns.Add("FaturaNo", typeof(string));
            dt.Columns.Add("FaturaTarihi", typeof(DateTime));
            dt.Columns.Add("ToplamMasraf", typeof(decimal));
            dt.Columns.Add("FaturalanacakTutar", typeof(decimal));
            dt.Columns.Add("DovizCinsi1Id", typeof(int));

            foreach (int rh in gridView2.GetSelectedRows())
            {
                DataRow r = gridView2.GetDataRow(rh);
                dt.Rows.Add(
                    r["FaturaId"].ToInt(),
                    r["CustomerId"].ToInt(),
                    r["REFERANS"].ToStr(),
                    r["GonderenId"].ToInt(),
                    r["FaturaNo"].ToStr(),
                    r["FaturaTarihi"].ToDate(),
                    r["ToplamMasraf"].ToDecimal(),
                    r["FaturalanacakTutar"].ToDecimal(),
                    r["DovizCinsi1Id"].ToInt()
                    );
            }

            return dt.Serialize();
        }

        void Faturalanacak(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show(gridView2.GetSelectedValues("FaturaId"), "Faturalanacak olarak işaretlenecek faturalar", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                ExecuteNonQuery("UpdMasrafFaturala", GetLines(), "Faturalanacak", WhoAmI);
                foreach (int rh in gridView2.GetSelectedRows())
                    gridView2.SetRowCellValue(rh, "Durum", "Faturalanacak");
                gridView2.BestFitColumns();
            }
        }

        //TODO: devamı??
        void IhracatFaturasinaEklenecek(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show(gridView2.GetSelectedValues("FaturaId"), "İhracat Faturasina Eklenecek faturalar", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                ExecuteNonQuery("UpdMasrafFaturala", GetLines(), "İhracat Faturasına Eklenecek", WhoAmI);
                foreach (int rh in gridView2.GetSelectedRows())
                    gridView2.SetRowCellValue(rh, "Durum", "İhracat Faturasına Eklenecek");
                gridView2.BestFitColumns();
            }
        }        

        void UreticiyeFaturalanacak(object sender, EventArgs e)
        {
            //using (UreticiyeFaturalanacak uf = new UreticiyeFaturalanacak(gridView2.GetSelectedValues("FaturaId")))
            //    if (uf.ShowDialog() == System.Windows.Forms.DialogResult.OK)

                if (XtraMessageBox.Show(gridView2.GetSelectedValues("FaturaId"), "Üreticiye Faturalanacak olarak işaretlenecek faturalar", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExecuteNonQuery("UpdMasrafFaturala", GetLines(), "Üreticiye Faturalanacak", WhoAmI);
                    foreach (int rh in gridView2.GetSelectedRows())
                        gridView2.SetRowCellValue(rh, "Durum", "Üreticiye Faturalanacak");
                    gridView2.BestFitColumns();
                }
        }

        void Faturalanmayacak(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show(gridView2.GetSelectedValues("FaturaId"), "Faturalanmayacak olarak işaretlenecek faturalar", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                ExecuteNonQuery("UpdMasrafFaturala", GetLines(), "Faturalanmayacak", WhoAmI);
                foreach (int rh in gridView2.GetSelectedRows())
                    gridView2.SetRowCellValue(rh, "Durum", "Faturalanmayacak");
                gridView2.BestFitColumns();
            }
        }

        void btnGetir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Rfrsh();
        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                switch (e.Column.FieldName)
                {
                    case "ToplamMasraf":
                    case "Durum":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        return;
                }
            }
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.ShowOnlyNonblankColumns();
            gridView2.YanYanaGetirSagina("ToplamMasraf", "FaturalanacakTutar", "DovizCinsi1Id", "Durum", "FaturalananTutar", "DovizCinsi2Id");
            gridView2.BestFitColumns();
        }

        private void Rfrsh()
        {
            gridView1.RefreshDataSource("GetImportList3x", beiAy1.EditValue.ToDate(), beiAy2.EditValue.ToDate(), txtReferans.EditValue.ToStr(), WhoAmI, REF);

            gridView1.ShowOnlyNonblankColumns();
            gridView2.ShowOnlyNonblankColumns();
            gridView2.YanYanaGetirSagina("ToplamMasraf", "FaturalanacakTutar", "DovizCinsi1Id", "Durum", "FaturalananTutar", "DovizCinsi2Id");
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

        }



    }
}
